<?php
namespace lib;

class Exception extends \Exception {

    /**
     * 抛出错误
     * @param $msg
     * @param $type
     */
    public static function error($msg, $type = E_USER_NOTICE){
        trigger_error($msg, $type);
    }

    /**
     * 抛出异常
     * @param $msg
     * @throws \Exception
     */
    public static function exception($msg){
        http_response_code(500);
        throw new \Exception($msg);
    }

    /**
     * 异常处理handler
     * @param \Exception $e
     */
    public static function ExceptionHandler(\Exception $e){
        self::displayErrorDetail(array(
            'type'  => 'exception',
            'message'   => $e->getMessage(),
            'file'  => $e->getFile(),
            'line'  => $e->getLine()
        ));
        exit;
    }

    /**
     * 错误处理handler
     * @param $level
     * @param $msg
     * @param $file
     * @param $line
     */
    public static function ErrorHandler($level, $msg, $file, $line){
        if(error_reporting() & $level){
            self::displayErrorDetail(array(
                'type'  => 'error',
                'level' => $level,
                'message'   => $msg,
                'file'  => $file,
                'line'  => $line
            ));
            exit;
        }
    }

    /**
     * 自定义的程序异常终止或者超时的处理方法
     */
    public static function shutdown(){
        $e = error_get_last();
        if($e){     //如果为真,则程序是意外终止
            self::displayErrorDetail($e);
        }
        exit;
    }

    /**
     * 打印错误细节
     */
    private static function displayErrorDetail($e){
        $view = new View();
        $content = array();
        if(isset($e['file'])){
            $line = 1;
            $end = $e['line'] + 6;
            $start = $e['line'] - 6 <= 0 ? 0 : $e['line'] - 6;
            $file = fopen($e['file'], "r") or exit("Unable to open file!");
            while(!feof($file)) {
                $con = fgets($file);
                if($line >= $start && $line <= $end){
                    $content[$line] = $con;
                }
                $line ++;
            }
            fclose($file);
            $e['path'] = pathinfo($e['file']);
        }
        $e['trace'] = debug_backtrace();
        foreach ($e['trace'] as $key => $val){
            $cache = explode('\\', $val['file']);
            $e['trace'][$key]['filename'] = end($cache);
        }
        $view->set('e', $e);
        $view->set('detail', $content);
        $view->display(TPL_PATH . 'shutdown.tpl');
    }

}